import pandas as pd
from sklearn.cluster import KMeans
import joblib
#
# # 读取源数据
# df = pd.read_csv("new_file_with_scores.csv")
#
# # 定义特征列
# features = ['Q10', 'Q12', 'Q13', 'Q14']
#
# best_clusters = None
# best_seed = None
# best_score = -float('inf')  # 初始化最好得分为负无穷大
#
# for seed in range(10):  # 尝试不同的随机种子值，例如从0到9
#     kmeans = KMeans(n_clusters=4, random_state=seed)  # 重新初始化KMeans对象
#     clusters = kmeans.fit_predict(df[features])  # 仅使用特征列进行聚类
#     score = kmeans.score(df[features])  # 获取聚类评分
#
#     # 检查当前结果是否比最好结果更好
#     if score > best_score:
#         best_clusters = clusters  # 保存最好的聚类结果
#         best_seed = seed  # 保存对应的随机种子值
#         best_score = score  # 保存最好得分
#
# # 保存最好的聚类结果
# joblib.dump(best_clusters, 'best_clusters.pkl')
#
# # 保存对应的随机种子值
# with open('best_seed.txt', 'w') as file:
#     file.write(str(best_seed))
#
import pandas as pd
import joblib
from sklearn.cluster import KMeans

# 读取源数据
df = pd.read_csv("new_file_with_scores.csv")

# 定义特征列
features = ['Q10', 'Q12', 'Q13', 'Q14']

# 加载之前保存的聚类结果
best_clusters = joblib.load('best_clusters.pkl')
# 加载之前保存的随机种子值
with open('best_seed.txt', 'r') as file:
    best_seed = int(file.read())

# 使用之前保存的随机种子值初始化KMeans对象
kmeans = KMeans(n_clusters=4, random_state=best_seed)
kmeans.fit(df[features])
cluster_centers = kmeans.cluster_centers_
kmeans = KMeans(n_clusters=4, random_state=best_seed)
kmeans.fit(df[features])
cluster_centers = kmeans.cluster_centers_
# # 将K-means聚类结果作为新的特征添加到数据集中
# df['kmeans_label'] = kmeans.labels_
# df.to_csv('new_file_with_scores_kmeans.csv',index=False)
# 打印特征列的聚类中心值
print("特征列的聚类中心值：")
print(cluster_centers)
# 特征列的聚类中心值：
# Q10           Q12         Q13         Q14
# [[7.02824859 5.38983051 9.23728814 6.54237288]    B
#  [5.70833333 1.9375     2.9375     3.4375    ]    D
#  [8.16949153 9.44067797 9.79661017 9.31355932]    A
#  [5.45454545 6.31818182 2.29545455 6.25      ]]   C
#
# import plotly.graph_objects as go
# features = ['Q10', 'Q12', 'Q13', 'Q14']
# cluster_centers = [
#     [7, 5, 9, 6],
#     [5, 1, 2, 3],
#     [8, 9, 9, 9],
#     [5, 6, 2, 6]
# ]
#
# # 定义评分阶段
# stages = ['B', 'D', 'A', 'C']
#
# # 按照评分阶段排序数据
# sorted_data = sorted(zip(stages, cluster_centers), key=lambda x: x[0])
#
# # 创建表格
# fig = go.Figure(data=[go.Table(
#     header=dict(values=['变量聚类', '基本认识', '主观意愿', '作用意义', '传播推广']),
#     cells=dict(values=[[x[0] for x in sorted_data],  # 行代表一个类别
#                        [x[1][0] for x in sorted_data],
#                        [x[1][1] for x in sorted_data],
#                        [x[1][2] for x in sorted_data],
#                        [x[1][3] for x in sorted_data]])
# )])
#
# # 显示表格
# fig.show()